package com.lhj.bootdemo.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lhj
 * @version 1.0
 * @date 2022/4/25 4:39 下午
 * @description:
 *
 *ThreadPoolExecutor执行顺序
 *
 *     线程池按以下行为执行任务
 *     1. 当线程数小于核心线程数时，创建线程。
 *     2. 当线程数大于等于核心线程数，且任务队列未满时，将任务放入任务队列。
 *     3. 当线程数大于等于核心线程数，且任务队列已满
 *         -1 若线程数小于最大线程数，创建线程
 *         -2 若线程数等于最大线程数，抛出异常，拒绝任务
 */

class ThreadPoolUtil {
    private static ExecutorService executorService = null;

    /**
     * 默认的拒绝策略
     * 丢弃任务，抛运行时异常
     * @return
     */
    public static ExecutorService getExecutorPool() {
        if (null == executorService) {
            executorService = new ThreadPoolExecutor(3, 5, 1L, TimeUnit.SECONDS, new ArrayBlockingQueue(4), Executors.defaultThreadFactory());
        }
        return executorService;
    }


    /**
     * 从队列中踢出最先进入队列（最后一个执行）的任务
     *
     * @return
     */
    public static ExecutorService getExecutorPoolForDiscardOldestPolicy() {
        if (null == executorService) {
            executorService = new ThreadPoolExecutor(3, 5, 1L, TimeUnit.SECONDS, new ArrayBlockingQueue(4), new ThreadPoolExecutor.DiscardOldestPolicy());
        }
        return executorService;
    }

    /**
     *忽视，什么都不会发生
     * @return
     */
    public static ExecutorService getExecutorPoolForDiscardPolicy() {
        if (null == executorService) {
            executorService = new ThreadPoolExecutor(3, 5, 1L, TimeUnit.SECONDS, new ArrayBlockingQueue(4), new ThreadPoolExecutor.DiscardPolicy());
        }
        return executorService;



    }


//    public static ExecutorService getExecutorPoolForDiscardPolicy() {
//        if (null == executorService) {
//            executorService = new ThreadPoolExecutor(3, 5, 1L, TimeUnit.SECONDS, new ArrayBlockingQueue(4), new ThreadPoolExecutor.DiscardPolicy());
//        }
//        return executorService;
//    }

}
